"""
    Author:
    Date: 2019-06-20

    主播动态管理类
"""

from apps.gma import helpers as gma_helpers
from entities.consts import *
from utils import db
from utils.log import Log

TABLE_NAME = 'cmf_users_moment'


def get_moment_count_by_auth_status(status, request=None):
    """ 根据审核状态获取动态数量 """
    apps_condition = gma_helpers.build_app_filter_condition_for_request(request)
    sql = f'''
        SELECT      COUNT(*) AS moment_count
        FROM        {TABLE_NAME} AS m
        JOIN        cmf_users_auth AS a ON m.uid=a.uid
        JOIN        cmf_users AS u ON u.id=m.uid
        WHERE       {apps_condition} AND
                    m.auth_status={status} AND
                    a.status={AUTH_STATUS_CERTIFIED};
    '''
    data = db.query_data_from_db(sql)
    return data[0]['moment_count'] if data else 0


def get_moment_list_by_auth_status(status, count, request=None):
    """ 根据审核状态获取动态列表 """
    apps_condition = gma_helpers.build_app_filter_condition_for_request(request)
    sql = f'''
        SELECT      p.*,
                    u.avatar,
                    u.nickname
        FROM        {TABLE_NAME} AS p
        JOIN        cmf_users AS u ON p.uid=u.id
        JOIN        cmf_users_auth AS a ON p.uid=a.uid
        WHERE       {apps_condition} AND
                    p.auth_status={status} AND
                    a.status={AUTH_STATUS_CERTIFIED}
        ORDER BY    p.update_time DESC
        LIMIT       {count};
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def get_moment_info(mid):
    """ 根据id查找动态信息 """
    sql = f'''
        SELECT      *
        FROM        {TABLE_NAME}
        WHERE       id={mid}
        LIMIT       1;
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


def update_moment_auth_status(mid, auth_status):
    """ 更新动态的认证状态 """
    sql = f'''
        UPDATE      {TABLE_NAME}
        SET         auth_status={auth_status}
        WHERE       id={mid}
        LIMIT       1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows == 1


def get_user_authing_moment_by(uid):
    """ 根据uid查找待审核的动态信息 """
    sql = f'''
        SELECT      *
        FROM        {TABLE_NAME}
        WHERE       uid={uid} AND
                    auth_status={AUTH_STATUS_WAITING}
        LIMIT       1;
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


def get_moment_resource(mid):
    """ 根据动态资源记录的ID查询动态资源记录 """
    sql = f'''
        SELECT      *
        FROM        cmf_users_moment_resource
        WHERE       moment_id={mid};
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def get_moment_resource_by_url(url):
    """ 根据动态资源的url查询动态资源记录 """
    sql = f'''
        SELECT      *
        FROM        cmf_users_moment_resource
        WHERE       resource_url="{url}";
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def get_user_last_moment(uid):
    """ 获取用户最新创建的动态记录 """
    sql = f'''
        SELECT      *
        FROM        cmf_users_moment
        WHERE       uid={uid}
        ORDER BY    id DESC
        LIMIT       1;
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


def create_video_moment(uid, video_url, title=''):
    """ 为用户创建视频动态 """
    # 防止同一个资源多次创建
    moments = get_moment_resource_by_url(video_url)
    if len(moments) > 0:
        Log.info(f"Create video moment skipped: uid={uid}, video={video_url}")
        return False

    # 创建动态数据
    Log.info(f"Create video moment: uid={uid}, video={video_url} ......")
    sql = '''
        INSERT INTO cmf_users_moment
        SET         uid=%(uid)s,
                    title=%(title)s,
                    moment_type=%(moment_type)s,
                    auth_status=%(auth_status)s;
    '''
    params = {
        'uid': str(uid),
        'title': title,
        'moment_type': str(MOMENT_VIDEO),
        'auth_status': str(VIDEO_AUTH_STATUS_AGREE),
    }
    affected_rows = db.execute_sql(sql, params)
    if affected_rows != 1:
        Log.error(f"Create video moment failed: uid={uid}, video={video_url}")
        return False

    # 获取动态id
    last_moment = get_user_last_moment(uid)
    if last_moment is None:
        Log.error(f"Create video moment failed for not find new created record: uid={uid}, video={video_url}")
        return False

    mid = last_moment['id']

    # 创建动态资源
    sql = '''
        INSERT INTO cmf_users_moment_resource
        SET         moment_id=%(mid)s,
                    resource_url=%(resource_url)s;
    '''
    params = {
        'mid': str(mid),
        'resource_url': str(video_url),
    }
    affected_rows = db.execute_sql(sql, params)
    if affected_rows != 1:
        Log.error(f"Create video moment resource failed: uid={uid}, mid={mid}, video={video_url}")
        return False

    Log.info(f"Create video moment: uid={uid}, video={video_url} ...... OK")
    return True


if __name__ == '__main__':
    print('ok')
